<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Linkslists;
use App\Models\Linkslistsviews;
use App\Models\Memberorders;
use App\Models\Users;
use App\Models\Linkslistsminapps;
use App\Models\Linkslistsips;
use App\Models\Linkslistshtmls;
use App\Models\Linkslistsshorts;
use App\Models\Linkslistsstyles;
use App\Models\Linkslistsipblack;
use App\Models\Linkslistssetting;
use App\Models\Linksliststhird;
use App\Models\Linkscard;
use App\Services\WechatService;
use App\Services\CommonService;
use App\Services\ApisafeService;
use App\Services\IpService;
use App\Services\WechatoffiaccountService;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use Log,Exception,Config;

class LinkController extends Controller
{    
    public function links(Request $request,$links_id)
    {
        // if(Cache::has('links_htmls_'.$links_id)) {
        //     $linkshtml = Cache::get('links_htmls_'.$links_id);
        //     return $linkshtml;
        // } else {
            $links = Linkslists::getLinks($links_id);
            if (empty($links)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($links->users_id == 7) {
                if (!in_array($links_id, ["1NRTqGkTjbd","cMrShf8F7AesOl","cMrt8384gJ1","sNdO1pR9R2","CMfpePb23A","1NRTqGkTjbd"])) {
                    return view('links.notice',["msg"=>"演示链接地址错误,请前往后台重新复制！"]);
                }
            }
            if ($links->disable == 2) return view('links.notice',["msg"=>"链接已被删除！"]);
            if ($links->end_time <= time()) {
                if ($links->limit_pv < 1000) {
                    return view('links.notice',["msg"=>"链接体验已过期,请开通会员后使用！"]);
                } else {
                    return view('links.notice',["msg"=>"链接已过期,请续费！"]);
                }
            }
            $linksStyles = Linkslistsstyles::getLinksListsStyles($links_id);
            if (empty($linksStyles)) $linksStyles = ["style"=>1,"logo"=>"","button_border"=>1,"button_background_color"=>"#06ae56","button_text_color"=>"#FFFFFF","botton_text"=>"点击立即前往微信","postion"=>1,"gif_show"=>1,"redirect_style"=>1,"redirect_url"=>""];
            $path = explode("?",$links->path);
            $query = count($path) > 1 ? $path[1] : "";
            if ($query == "" && in_array($links->platfrom_type, [1,2,3,8,9,11,12])) {
                $query = "id=".$links_id."&platfrom_type=".$links->platfrom_type;
            } elseif(in_array($links->platfrom_type, [14,15,16])) {
                $linkSetting = Linkslistssetting::getLinksListsSetting($links_id);
                $query = "id=".$links_id."&sph_id=".$linkSetting->sph_id."&sph_spid=".$linkSetting->sph_spid."&sph_img=".$linkSetting->sph_img."&platfrom_type=".$links->platfrom_type;
            } elseif(in_array($links->platfrom_type, [1,13])) {
                $query = $query."&url=".urlencode($links->msg)."&platfrom_type=".$links->platfrom_type."&msg=1";
            } else {
                $query = $query."&platfrom_type=".$links->platfrom_type;
            }
            if ($links->platfrom_type == 6) {
                $LinksListsThird = Linksliststhird::getLinksListsThird($links_id);
                $third_original_id = $LinksListsThird->original_id;
                $third_path = $LinksListsThird->path;
            } else {
                $third_original_id = "";
                $third_path = "";
            }
            $msg = in_array($links->platfrom_type, [1,13]) ? $links->msg : "";
            $linksHtml = Linkslistshtmls::linksListHtml($links_id);
            if (empty($linksHtml)) {
                $linksHtml = (object)["copyright"=>1,"html"=>'<div class="edit-htmldom htmldom-activity" id="YY76ERh23nRrHAzHc53w6NjfayXNc7T6" platfrom="img"><img draggable="false" src="https://doye.oss-cn-beijing.aliyuncs.com/uploads/20230201/202302011408065115.jpg" class="site-img-12"></div><div class="edit-htmldom" id="6KAhRPwiWQs4wWwTiGFixH8txCXx7CrB" platfrom="wechat" platfrom_detial="wechat_one"><div class="wechat_one" onclick="simpleSubmit();"><i class="iconfont icon-weixin"></i><font>点击立即前往微信</font></div></div><p class="copy-notice"><font></font><span id="copylink" data-clipboard-text="">复制链接</span></p>'];
            }
            $linksinfo = ApisafeService::aesEncryptDefault(json_encode(["links_id"=>$links_id,"appid"=>$links->appid,"path"=>$path[0],"query"=>$query,"third_original_id"=>$third_original_id,"third_path"=>$third_path,"miniapp_type"=>$links->miniapp_type,"platfrom_type"=>$links->platfrom_type,"type"=>$links->type,"original_id"=>$links->original_id,"disable"=>$links->disable,"users_id"=>$links->users_id,"msg"=>$msg,"styles"=>$linksStyles,"copyright"=>$linksHtml->copyright]));
            $linkCard = Linkscard::linkCardDetial($links_id);
            $linkshtml = view("links.links_template_html",["title"=>$links->title,"linksinfo"=>$linksinfo,"linksHtml"=>$linksHtml,"style"=>$linksStyles["style"],"linkCard"=>$linkCard])->render();

            // 每次调用缓存2小时
            // Cache::put('links_htmls_'.$links_id, $linkshtml, 7200);
            return $linkshtml;
        // }
    }

    public function tetslinks(Request $request,$links_id)
    {
        Log::info("tetslinks---------------");
        Log::info($links_id);
        Log::info("tetslinks---------------");
        return view('links.notice',["msg"=>"维护中,具体请联系客服!"]);
        // if(Cache::has('links_html_'.$links_id)) {
        //     $links = Cache::get('links_html_'.$links_id);
        //     return view("links.links_template_test",["title"=>$links["title"],"describe"=>$links["describe"],"linksinfo"=>$links["linksinfo"]]);
        // } else {
        //     $links = Linkslists::getLinks($links_id);
        //     if (empty($links)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
        //     if ($links->users_id == 7) return view('links.notice',["msg"=>"演示链接地址错误,请前往后台重新复制！"]);
        //     if ($links->disable == 2) return view('links.notice',["msg"=>"链接已被删除！"]);
        //     if ($links->end_time <= time()) {
        //         if ($links->limit_pv < 1000) {
        //             return view('links.notice',["msg"=>"链接体验已过期,请开通会员后使用！"]);
        //         } else {
        //             return view('links.notice',["msg"=>"链接已过期,请续费！"]);
        //         }
        //     }
        //     $linksStyles = Linkslistsstyles::getLinksListsStyles($links_id);
        //     if (empty($linksStyles)) $linksStyles = ["style"=>1,"logo"=>"","button_border"=>1,"button_background_color"=>"#06ae56","button_text_color"=>"#FFFFFF","botton_text"=>"点击立即前往微信","postion"=>1,"gif_show"=>1,"redirect_style"=>1,"redirect_url"=>""];
        //     $path = explode("?",$links->path);
        //     $query = count($path) > 1 ? $path[1] : "";
        //     if ($query == "" && in_array($links->platfrom_type, [1,2,3,8,9,11,12])) {
        //         $query = "id=".$links_id;
        //     }
        //     $msg = in_array($links->platfrom_type, [1,13]) ? $links->msg : "";
        //     $linksinfo = ApisafeService::aesEncryptDefault(json_encode(["links_id"=>$links_id,"appid"=>$links->appid,"path"=>$path[0],"query"=>$query,"miniapp_type"=>$links->miniapp_type,"platfrom_type"=>$links->platfrom_type,"type"=>$links->type,"original_id"=>$links->original_id,"disable"=>$links->disable,"users_id"=>$links->users_id,"urlscheme"=>$links->urlscheme,"wechat"=>$links->wechat,"msg"=>$msg,"styles"=>$linksStyles]));

        //     // 每次调用缓存30分钟
        //     Cache::put('links_html_'.$links_id, ["title"=>$links->title,"describe"=>$links->describe,"linksinfo"=>$linksinfo,"users_id"=>$links->users_id], 1800);
        //     return view("links.links_template_test",["title"=>$links->title,"describe"=>$links->describe,"linksinfo"=>$linksinfo]);
        // }
    }

    public function ossLinksHtml(Request $request,$filepath,$links_id)
    {
        // 以前的OSS跳转，测试没毛病可以删除
        return redirect("/l/".$links_id);
    }

    public function linksCopy(Request $request,$links_id)
    {
        if(Cache::has('links_copy_'.$links_id)) {
            $listsSetting = Cache::get('links_copy_'.$links_id);
        } else {
            $listsSetting = Linkslistssetting::getLinksListsSetting($links_id);
            if (empty($listsSetting)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            $linksLists = Linkslists::getLinksSimple($links_id);
            if (empty($linksLists)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($linksLists->disable == 2) return view('links.notice',["msg"=>"链接已被删除！"]);
            if ($linksLists->end_time <= time()) return view('links.notice',["msg"=>"会员已过期,请充值！"]);
            if ($linksLists->left_pv <= 1) return view('links.notice',["msg"=>"链接访问量不足,请升级会员！"]);
            $listsSetting->title = $linksLists->title;
            $listsSetting->description = $linksLists->describe;
            $listsSetting->type = $linksLists->type;
            // 每次调用缓存30分钟
            Cache::put('links_copy_'.$links_id, $listsSetting, 1800);
        }
        return view("links.wechat_add",["listsSetting"=>$listsSetting]);
    }

    public function linksSpare(Request $request,$links_id)
    {   
        if(Cache::has('links_spare_'.$links_id)) {
            $listsSetting = Cache::get('links_spare_'.$links_id);
        } else {
            $listsSetting = Linkslistssetting::getLinksListsSetting($links_id);
            if (empty($listsSetting)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            $linksLists = Linkslists::getLinksSimple($links_id);
            if (empty($linksLists)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($linksLists->disable == 2) return view('links.notice',["msg"=>"链接已被删除！"]);
            if ($linksLists->end_time <= time()) return view('links.notice',["msg"=>"会员已过期,请充值！"]);
            if ($linksLists->left_pv <= 1) return view('links.notice',["msg"=>"链接访问量不足,请升级会员！"]);
            $listsSetting->title = $linksLists->title;
            $listsSetting->description = $linksLists->describe;
            $listsSetting->platfrom_type = $linksLists->platfrom_type;
            $listsSetting->type = $linksLists->type;
            // 每次调用缓存30分钟
            Cache::put('links_spare_'.$links_id, $listsSetting, 1800);
        }
        return view("links.links_spare",["listsSetting"=>$listsSetting]);
    }

    // 朋友圈分享模式
    public function linksShare(Request $request,$links_id)
    {   
        if(Cache::has('links_share_'.$links_id)) {
            $listsSetting = Cache::get('links_share_'.$links_id);
        } else {
            $listsSetting = Linkslistssetting::getLinksListsSetting($links_id);
            if (empty($listsSetting)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            $linksLists = Linkslists::getLinksSimple($links_id);
            if (empty($linksLists)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($linksLists->disable == 2) return view('links.notice',["msg"=>"链接已被删除！"]);
            if ($linksLists->platfrom_type != 10) return view('links.notice',["msg"=>"链接类型错误！"]);
            if ($linksLists->end_time <= time()) return view('links.notice',["msg"=>"会员已过期,请充值！"]);
            if ($linksLists->left_pv <= 1) return view('links.notice',["msg"=>"链接访问量不足,请升级会员！"]);
            $listsSetting->title = $linksLists->title;
            $listsSetting->description = $linksLists->describe;
            $listsSetting->end_time = $linksLists->end_time;
            $listsSetting->msg = $linksLists->msg;
            $listsSetting->type = $linksLists->type;
            // 每次调用缓存30分钟
            Cache::put('links_share_'.$links_id, $listsSetting, 1800);
        }
        return view("links.wechat_share",["listsSetting"=>$listsSetting]);
    }

    // 演示专用链接
    public function testLinks(Request $request,$links_id)
    {
        return view('links.warn',["msg"=>"演示链接已升级,<br>请联系客服获取最新的演示链接!"]);
    }

    // 短链接
    public function shortLinks(Request $request,$short_id)
    {
        $ua = $_SERVER['HTTP_USER_AGENT'];
        // 如果包含中文则移除
        if (preg_match("/[\x7f-\xff]/", $short_id)) {
            $short_id = CommonService::getSHortLinksId($short_id);
        }
        $links = Linkslistsshorts::getLinksListsId($short_id);
        if (empty($links)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
        return redirect()->away(config('spare_urls.paidurl')."/l/".$links->links_id);
    }

    // 自定义页面,小程序使用
    public function customLinks(Request $request,$links_id)
    {
        return view('links.notice',["msg"=>"本方法已无法使用,请使用新模式！"]);
    }

    //点击版专用跳转
    public function urllinkClick(Request $request,$links_id)
    {
        if(Cache::has('links_id_'.$links_id)) {
            $links = Cache::get('links_id_'.$links_id);
        } else {
            $links = Linkslists::getLinks($links_id);
            if (empty($links)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($links->disable == 2) return view('links.notice',["msg"=>"链接已删除,请使用其他链接！"]);
            if ($links->limit_status == 1 && $links->left_pv < 1) return view('links.notice',["msg"=>"链接访问次数不足,请充值！"]);
            if ($links->limit_pv >= 10000 && $links->end_time < time()) return view('links.notice',["msg"=>"会员已过期,请充值！"]);
            // 每次调用缓存30分钟
            Cache::put('links_id_'.$links_id, $links, 1800);
        }
        $linksListsMinapps = Linkslistsminapps::getUseableMinapps($links->users_id);
        if (empty($linksListsMinapps)) return view('links.notice',["msg"=>"您还没有独家小程序,快联系客服获取吧！"]);
        if (empty($linksListsMinapps->secret)) return view('links.notice',["msg"=>"本模式小程序必须使用密钥模式！"]);
        $paths = explode("&path=",$request->path);
        if (count($paths) >= 2) {
            $query = $paths[0]."&path=".urlencode($paths[1]);
        } else {
            $query = $paths[0];
        }
        $urllink = WechatService::generateShortUrlLink($linksListsMinapps->appid,$linksListsMinapps->secret,"/pages/index/request",$query);
        if ($urllink["status"] == "success") {
            return redirect()->away($urllink["url_link"]);
        } else {
            return view('links.notice',["msg"=>$urllink["msg"]]);
        }
    }

    public function linksApi(Request $request,$id)
    {
        $links = Linkslists::getApiLinks($id);
        if (empty($links)) return response()->json(['status' => "error", 'code' => "1001", 'msg' => "您访问的链接不存在！", 'data' => []]);
        if ($links->limit_status == 1 && $links->month_pv > $links->limit_pv) return response()->json(['status' => "error", 'code' => "1001", 'msg' => "链接访问次数不足,请充值！", 'data' => []]);
        if ($links->limit_pv >= 10000 && $links->end_time < time())  return response()->json(['status' => "error", 'code' => "1001", 'msg' => "会员已过期,请充值！", 'data' => []]);
        if ($links->limit_pv < 1000 && $links->end_time < time()) return response()->json(['status' => "error", 'code' => "1001", 'msg' => "页面不存在！", 'data' => []]);
        if (in_array($links->platfrom_type, [8,9,11])) {
            $msg = config('spare_urls.miniurl')."/article/".$id;
            $url = config('spare_urls.miniurl')."/article/".$id;
        } else {
            $msg = $links->msg;
            $url = $links->msg;
        }
        if (in_array($links->platfrom_type, [2,3])) {
            $links->platfrom = 3;
        } elseif($links->platfrom_type == 6) {
            $links->platfrom = 2;
        } else {
            $links->platfrom = 1;
        }
        // 紧急活动不统计访问量等其他数据
        if ($links->type == 1) {
            $data = ["title"=>$links->title,"platfrom"=>$links->platfrom,"describe"=>$links->describe,"type"=>$links->type,"msg"=>$msg,"status"=>$links->status,"url"=>$url,"id"=>$links->id,"links_id"=>$links->links_id,"image"=>$links->image,"notice"=>$links->notice,"describe_show"=>$links->describe_show,"notice_img"=>$links->notice_img];
        } else {
            try {
                if (strlen($id) <= 11) {
                    $ip = $_SERVER['REMOTE_ADDR'];
                    $lastips = Linkslistsips::getLinksLastIps($id,$ip);
                    if (empty($lastips)) {
                        $ipinfo = IpService::getAddressByIp($ip);
                        $system = 1;
                        $device = 1;
                        $browser = 1;
                        $province = mb_substr($ipinfo["province"], 0, 9);
                        $city = mb_substr($ipinfo["city"], 0, 14);
                        Linkslistsips::creatLinksIps($id,$province,$city,$system,$device,$browser,$ip,3,"");
                    } else {
                        // 不重复更新数据
                        if ($lastips->status == 1) {
                            Linkslistsips::updateLinksIpsStatus($lastips->id,2,1);
                        }
                    }
                }
            } catch (Exception $e) {
                Log::info("小程序访问统计异常！");
                Log::info($e);
            }

            $data = ["title"=>$links->title,"platfrom"=>$links->platfrom,"describe"=>$links->describe,"type"=>$links->type,"msg"=>$msg,"status"=>$links->status,"url"=>$url,"id"=>$links->id,"links_id"=>$links->links_id,"image"=>$links->image,"notice"=>$links->notice,"describe_show"=>$links->describe_show,"notice_img"=>$links->notice_img];
        }
        return response()->json(['status' => "success", 'code' => "1000", 'msg' => "获取成功", 'data' => $data]);
    }

    public function openMiniapp(Request $request,$links_id)
    {
        // 如果不是跳转专属域名,直接跳转
        if(strpos(config('spare_urls.spareurl'),$_SERVER["HTTP_HOST"]) === false) return redirect()->away(config('spare_urls.spareurl')."/openminiapp/".$links_id);
        if(Cache::has('links_id_'.$links_id)) {
            $links = Cache::get('links_id_'.$links_id);
        } else {
            $links = Linkslists::getLinks($links_id);
            if (empty($links)) return view('links.notice',["msg"=>"链接不存在,请核实链接是否正确！"]);
            if ($links->disable == 2) return view('links.notice',["msg"=>"链接已删除,请使用其他链接！"]);
            if ($links->limit_status == 1 && $links->left_pv < 1) return view('links.notice',["msg"=>"链接访问次数不足,请充值！"]);
            if ($links->limit_pv >= 10000 && $links->end_time < time()) return view('links.notice',["msg"=>"会员已过期,请充值！"]);
            // 每次调用缓存30分钟
            Cache::put('links_id_'.$links_id, $links, 1800);
        }
        try {
            $accessToken = WechatoffiaccountService::officialAccessToken(false);
        } catch (Exception $e) {
            $errormsg = $e->getMessage();
            $message = json_decode(str_replace("Request access_token fail: ", "", $errormsg));
            if (empty($message)) return view('links.notice',["msg"=>"链接出现异常,请联系客服处理！"]);
            if ($message->errcode == 40164) return view('links.notice',["msg"=>"小程序未设置IP白名单,请在小程序后台关闭IP限制！"]);
            return view('links.notice',["msg"=>"链接出现异常,请联系客服处理！"]);
        }
        $config = Config::get("weixin.offiaccount.ttwl");
        // 必须认证,天天外链
        $appid = $config["app_id"]; //填入服务号AppID
        if (!isset($accessToken["access_token"])) return view('links.notice',["msg"=>"接口异常,请稍后尝试1！"]);
        $access_token = $accessToken["access_token"];
        $tickets = WechatService::getTicket($appid,$access_token);
        if (!isset($tickets["ticket"])) return view('links.notice',["msg"=>"接口异常,请稍后尝试2！"]);
        $ticket = $tickets["ticket"];
        $timestamp = time();

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        $http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? "https://":"http://";
        $url = $http.$_SERVER["HTTP_HOST"]."/openminiapp/".$links_id; // 调用JSSDK的页面地址

        // 4.小程序(密钥版)5.小程序(Urlscheme版)
        if (in_array($links->platfrom_type, [4,5])) {
            $username = $links->original_id;
            $path = empty($request->path) ? $links->path : $request->path;
            if (!empty($request->path)) {
                $url = $url."?path=".urlencode($request->path);
            }
        } elseif ($links->platfrom_type == 6) {
            $LinksListsThird = Linksliststhird::getLinksListsThird($links_id);
            $username = isset($LinksListsThird->original_id) ? $LinksListsThird->original_id : $links->original_id;
            if (isset($LinksListsThird->original_id)) {
                $path = empty($LinksListsThird->path) ? "" : $LinksListsThird->path;
            } else {
                $timestamp = time()+600;
                $key = substr($links->appid,0,16);
                $iv = $timestamp."WLWLWL";
                $sign = md5("wl".$iv.$key.$iv."lw");
                $path = "/pages/index/request?id=".$links_id."&key=".$key."&timestamp=".$timestamp."&nsign=".$sign;
            }
        } elseif (in_array($links->platfrom_type, [14,15,16])) {
            $username = $links->original_id;
            $timestamp = time()+600;
            $key = substr($links->appid,0,16);
            $iv = $timestamp."WLWLWL";
            $sign = md5("wl".$iv.$key.$iv."lw");
            $linkSetting = Linkslistssetting::getLinksListsSetting($links_id);
            $path = "/pages/index/request?id=".$links_id."&key=".$key."&timestamp=".$timestamp."&nsign=".$sign."&sph_id=".$linkSetting->sph_id."&sph_spid=".$linkSetting->sph_spid."&sph_img=".$linkSetting->sph_img."&platfrom_type=".$links->platfrom_type;
        } else {
            $username = $links->original_id;
            $timestamp = time()+600;
            $key = substr($links->appid,0,16);
            $iv = $timestamp."WLWLWL";
            $sign = md5("wl".$iv.$key.$iv."lw");
            $path = "/pages/index/request?id=".$links_id."&key=".$key."&timestamp=".$timestamp."&nsign=".$sign;
        }

        if(Cache::has('links_style_'.$links_id)) {
            $styles = Cache::get('links_style_'.$links_id);
        } else {
            $styles = Linkslistsstyles::getLinksListsStyles($links_id);
            if (empty($styles)) $styles = ["style"=>1,"logo"=>"","button_border"=>1,"button_background_color"=>"#06ae56","button_text_color"=>"#FFFFFF","botton_text"=>"点击立即前往微信","postion"=>1,"gif_show"=>1,"redirect_style"=>1,"redirect_url"=>""];
            // 每次调用缓存30分钟
            Cache::put('links_style_'.$links_id, $styles, 1800);
        }

        if ($styles["style"] == 5) {
            $linksHtml = Linkslistshtmls::getLinksListsHtml($links_id,2);
        } else {
            $linksHtml = [];
        }
         
        $signature = sha1("jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}");
        return view('links.open_miniapp',["appid"=>$appid,"links_id"=>$links_id,"timestamp"=>$timestamp,"nonceStr"=>$nonceStr,"signature"=>$signature,"ticket"=>$ticket,"username"=>$username,"path"=>$path,"links"=>$links,"styles"=>$styles,"linksHtml"=>$linksHtml]);
    }

    public function getLocation(Request $request)
    {
        $accessToken = WechatoffiaccountService::officialAccessToken();
        $config = Config::get("weixin.offiaccount.ttwl");
        // 必须认证,天天外链
        $appid = $config["app_id"]; //填入服务号AppID
        $secret = $config["secret"]; //填入服务号AppSecret
        if (!isset($accessToken["access_token"])) return view('links.notice',["msg"=>"接口异常,请稍后尝试1！"]);
        $access_token = $accessToken["access_token"];
        $tickets = WechatService::getTicket($appid,$access_token);
        if (!isset($tickets["ticket"])) return view('links.notice',["msg"=>"接口异常,请稍后尝试2！"]);
        $ticket = $tickets["ticket"];
        $timestamp = time();

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        $http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? "https://":"http://";
        $url = $http.$_SERVER["HTTP_HOST"]."/getlocation"; // 调用JSSDK的页面地址
         
        $signature = sha1("jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}");
        return view('links.get_location',["appid"=>$appid,"timestamp"=>$timestamp,"nonceStr"=>$nonceStr,"signature"=>$signature,"ticket"=>$ticket]);
    }

    public function dynamicLinks(Request $request,$links_id)
    {
        return view('links.dynamic_wechat');
    }

    public function jsLinksMiniapp(Request $request)
    {
        header('Access-Control-Allow-Origin:*');
        $links_id = $request->links_id;
        $links = Linkslists::getLinks($links_id);
        if (empty($links)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"链接不存在！"]);
        $access_token = Redis::get("web_miniapp_access_token".$links_id);
        
        // 4.小程序(密钥版)5.小程序(Urlscheme版)
        if (in_array($links->platfrom_type, [4,5])) {
            // 私人部署小程序
            $msg = json_decode($links->msg);
            $mini_id = $msg->mini_id;
            // 获取本小程序配置的小程序
            $minapps = Linkslistsminapps::getMiniUseableMinapps($links->users_id,$mini_id);
            if (!empty($minapps)) {
                $username = $minapps->original_id;
                $path = $msg->path;
            } else {
                if ($links->platfrom_type == 5) {
                    if (isset($msg->original_id)) {
                        $username = $msg->original_id;
                        $path = empty($msg->path) ? "/pages/index/index" : $msg->path;
                    }
                } else {
                    return response()->json(["status"=>"error","code"=>"1004","msg"=>"无可跳转的小程序,请联系客服！"]);
                }
            }
        } else {
            // 先获取自己私人小程序
            $minapps = Linkslistsminapps::getUseableMinapps($links->users_id);
            if (empty($minapps)) {
                if ($links->imit_pv > 1000) {
                    if ($links->platfrom_type == 1){
                        $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(2);
                    } elseif (in_array($links->platfrom_type, [2,3])){
                        $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(4);
                    } elseif (in_array($links->platfrom_type, [8,9,11])){
                        $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(3);
                    } elseif ($links->platfrom_type == 6){
                        $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(5);
                    } else {
                        $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(1);
                    }
                } else {
                    $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(6);
                }
            }
            if (empty($minapps)) return response()->json(["status"=>"error","code"=>"1005","msg"=>"无可跳转的小程序,请联系客服！"]);
            $username = $minapps->original_id;
            $path = "/pages/index/request?id=".$links_id;
        }

        // 必须认证,每日鲜粮
        $appid = $minapps->wechat_appid; //填入服务号AppID
        $secret = $minapps->wechat_secret; //填入服务号AppSecret
        if (empty($access_token)) {
            $token = WechatService::getToken($appid,$secret);
            if (isset($token["access_token"])) {
                Redis::setex('web_miniapp_access_token'.$links_id, 7000, $token["access_token"]);
                $access_token = $token["access_token"];
            } else {
                return response()->json(["status"=>"error","code"=>"1005","msg"=>"接口异常,请联系客服处理！"]);
            }
        }
        $tickets = WechatService::getTicket($appid,$access_token);
        if (!isset($tickets["ticket"])) return response()->json(["status"=>"error","code"=>"1005","msg"=>"接口异常,请联系客服处理！"]);
        $ticket = $tickets["ticket"];
        $timestamp = time();

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $url = urldecode($request->url); // 调用JSSDK的页面地址
        $signature = sha1("jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}");
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"链接获取成功！","data"=>["appid"=>$appid,"links_id"=>$links_id,"timestamp"=>$timestamp,"nonceStr"=>$nonceStr,"signature"=>$signature,"ticket"=>$ticket,"username"=>$username,"path"=>$path]]);
    }

    public function articleDetial(Request $request,$links_id)
    {
        $sign = CommonService::md5Encrypt($links_id);
        return view("links.article",["links_id"=>$links_id,"sign"=>$sign]);
    }

    public function wechats(Request $request)
    {
        return view("links.wechat");
    }

    public function error500(Request $request)
    {
        abort(404, '您找的网站不存在！');
    }

    public function linksIpStatistics(Request $request)
    {
        header('Access-Control-Allow-Origin:*');
        $links_id = $request->links_id;
        // if (strlen($links_id) >= 11) return response()->json(["status"=>"error","code"=>"1001","msg"=>"本数据不再统计！"]);
        $ip = $_SERVER['REMOTE_ADDR'];
        // 根据IP获取城市信息
        $ipinfo = IpService::getAddressByIp($ip);
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $system = CommonService::userAgentSystem();
        $device = CommonService::userAgentDevice();
        $browser = CommonService::userAgentBrowser();
        $model = "";
        Log::info("linksIpStatistics------");
        Log::info($request->all());
        Log::info($id);
        Log::info("linksIpStatistics------");
        Linkslistsips::creatLinksIps($links_id,$ipinfo["province"],$ipinfo["city"],$system,$device,$browser,$ip,1,"");

        return response()->json(["status"=>"success","code"=>"1000","msg"=>"数据保存成功！"]);
    }

    public function jsLinksDetial(Request $request)
    {
        return view('links.notice',["msg"=>"接口暂停使用！"]);
    }

    public function linksCompatible(Request $request)
    {
        return view('links.compatible');
    }
}
